package com.ruoyi.city.service.impl;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.department.domain.Department;
import com.ruoyi.economize.domain.Economize;
import com.ruoyi.economize.mapper.EconomizeMapper;
import com.ruoyi.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.city.mapper.CityMapper;
import com.ruoyi.city.domain.City;
import com.ruoyi.city.service.ICityService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-09
 */
@Service
public class CityServiceImpl implements ICityService 
{
    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private EconomizeMapper economizeMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public City selectCityById(Long id)
    {
        return cityMapper.selectCityById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param city 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<City> selectCityList(City city)
    {
        return cityMapper.selectCityList(city);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param city 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertCity(City city)
    {
        return cityMapper.insertCity(city);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param city 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateCity(City city)
    {
        return cityMapper.updateCity(city);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCityByIds(Long[] ids)
    {
        return cityMapper.deleteCityByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCityById(Long id)
    {
        return cityMapper.deleteCityById(id);
    }

    /**
     * 根据省查询市
     *
     * @param economizeId
     * @return
     */
    @Override
    public List<City> selectCityListByEconomizeId(Long economizeId) {
        City city = new City();
        city.setEconomizeId(economizeId);
        return cityMapper.selectCityList(city);
    }

    @Override
    public AjaxResult addFile(MultipartFile file) throws IOException {
        ExcelUtil<City> util = new ExcelUtil<>(City.class);
        List<City> cityList = util.importExcel(file.getInputStream());

        // 先对 diseaseList 中的 illnessName 和 departmentName 去前后空格
        cityList.forEach(city -> {
            if (city.getCity() != null) {
                city.setCity(city.getCity().trim());
            }
        });

        // ✅ 1. Excel 中按城市名去重（保留第一条）
        Map<String, City> uniqueCityMap = cityList.stream()
                .filter(city -> StringUtils.isNotBlank(city.getCity()))
                .collect(Collectors.toMap(
                        City::getCity,
                        city -> city,
                        (existing, replacement) -> existing
                ));
        List<City> uniqueExcelList = new ArrayList<>(uniqueCityMap.values());

        // ✅ 2. 查询数据库中已有城市
        List<City> existingCities = cityMapper.selectCityList(new City());
        Set<String> existingCityNames = existingCities.stream()
                .map(City::getCity)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        // ✅ 3. 过滤掉数据库中已有的城市
        List<City> newCities = uniqueExcelList.stream()
                .filter(city -> !existingCityNames.contains(city.getCity()))
                .collect(Collectors.toList());

        int successCount = 0;
        for (City city : newCities) {
            // ✅ 4. 绑定经济区，确保存在并处理 null 情况
            Economize economize = economizeMapper.selectEconomizeByName(city.getEconomizeName());
            if (economize == null) {
                continue; // 未找到经济区，跳过该城市
            }

            city.setEconomizeId(economize.getId());
            cityMapper.insertCity(city);
            successCount++;
        }

        return AjaxResult.success("导入成功，共导入 " + successCount + " 条新城市数据");
    }

}
